<?php


namespace app\api\controller;


use app\admin\model\Address;
use app\admin\model\GoodsSkuValue;
use app\admin\model\User;
use app\admin\model\UserPintuanLog;
use app\common\controller\Api;
use app\admin\model\Goods as GoodsModel;
use app\common\model\Config;
use think\Db;
use think\Env;

class Collage extends Api
{
    protected $noNeedLogin = ['collage'];
    protected $noNeedRight = ['*'];


    /**
     * 拼购显示
     *
     */
    public function index()
    {
        $goods = GoodsModel::where(['type' => 2, 'status' => 1])
            ->where('out_time', '<', time())
            ->field('id,image,sell,title,subtitle,service,address,content,out_time,value_id')
            ->select();
        $config = Config::find(19);
        if (!empty($goods)) {
            foreach ($goods as &$v) {
                $value = GoodsSkuValue::where('id', 'in', $v['value_id'])
                    ->with('sku')
                    ->field('id,name,sku_id')
                    ->select();
                $sku = [];
                foreach ($value as &$vv) {
                    $sku[$vv['sku_id']]['name'] = $vv['sku']['name'];
                    unset($vv['sku']);
                    $sku[$vv['sku_id']]['values'][] = $vv;
                    //$vv['sku_id'] = $sku['name'];
                }
                $v['value_id'] = $sku;
                $image = explode(',', $v['image']);
                $domain = [];
                foreach ($image as $vvv) {
                    $domain[] = Env::get('app.yuming') . $vvv;
                }
                $v['image'] = $domain;
                $v['content'] = get_img_thumb_url($v['content']);
                $v['out_time'] = date('Y-m-d H:i:s', $v['out_time']);
                $v['price'] = $config['value'];
                $v->unsetAppend();
                unset($v);
            }
        }
        $this->success('获取成功', $goods);
    }

    /**
     * 拼购
     *
     */
    public function collage()
    {
        if ($this->request->isPost()) {
            $ress = Address::where(['is_default' => 1, 'user_id' => $this->auth->id])->find();
            $address_id = input('address_id', $ress['id']);     //收货地址
            $address = Address::field('id,name,phone,city,address,is_default')->find($address_id); //地址
            $address->unsetAppend();
            $package = '0.00';       //运费
            $goods = GoodsModel::where(['type' => 2, 'status' => 1])
                ->where('out_time', '<', time())
                ->field('id,image,title,value_id')
                ->select();
            $con = Config::find(19);
            $price = $con['value'];
            if (!empty($goods)) {
                foreach ($goods as &$v) {
                    $image = explode(',', $v['image']);
                    if (isset($image[0])) {
                        $v['image'] = Env::get('app.yuming') . $image[0];
                    }
                    $value = GoodsSkuValue::where('id', 'in', $v['value_id'])
                        ->with('sku')
                        ->field('id,name,sku_id')
                        ->select();
                    $sku = [];
                    foreach ($value as &$vv) {
                        $sku[$vv['sku_id']]['name'] = $vv['sku']['name'];
                        unset($vv['sku']);
                        $sku[$vv['sku_id']]['values'][] = $vv;
                        //$vv['sku_id'] = $sku['name'];
                    }
                    $v['value_id'] = $sku;
                    $v->unsetAppend();
                    unset($v);
                }
            }
            $data = ['address' => $address, 'goods' => $goods, 'price' => $price,'package' => $package];
            $this->success('获取成功', $data);
        }
        $this->error('无效请求');

    }

    /**
     *
     * 立即兑换
     */
    public function exchange()
    {
        if ($this->request->isPost()) {
            $ress = Address::where(['is_default' => 1, 'user_id' => $this->auth->id])->find();
            $address_id = input('address_id', $ress['id']);     //收货地址
            $goods_id = input('goods_id');                      //商品
            $sku_id = input('value_id');                        //规格
            $goods = GoodsModel::field('id,title,subtitle,image')->find($goods_id);
            $address = Address::field('id,name,phone,city,address,is_default')->find($address_id); //地址
            $goods->unsetAppend();
            $address->unsetAppend();
            $con = Config::find(19);
            $price = $con['value'];
            $package = '包邮';       //运费
            if ($goods) {
                $image = explode(',', $goods['image']);
                if (isset($image[0])) {
                    $goods['image'] = Env::get('app.yuming') . $image[0];
                }
                $sku = '';
                if ($sku_id) {
                    $sku_value = GoodsSkuValue::where('id', 'in', $sku_id)
                        ->column('name');
                    $sku = implode(',', $sku_value);
                }
            }
            $data = ['address' => $address, 'goods' => $goods, 'sku_value' => $sku, 'package' => $package, 'price' =>$price];
            $this->success('获取成功', $data);
        }
        $this->error('无效请求');
    }


    /**
     *
     * 提交订单
     */
    public function order()
    {
        if ($this->request->isPost()) {
            $goods_id = input('goods_id');
            if (empty($goods_id)) {
                $this->error('请选择商品');
            }
            $address_id = input('address_id');
            if (empty($address_id)) {
                $this->error('请选择地址');
            }
            $value_id = input('value_id', '');   //规格id
            $user = User::find($this->auth->id);
            $goods = GoodsModel::where('id', $goods_id)
                ->field('id,title,subtitle,stock,image,value_id')
                ->find();
            if (!$goods) {
                $this->error('商品错误');
            }
            if (!empty($goods['value_id'])) {
                if (empty($value_id)) {
                    $this->error('请选择商品规格');
                }
            }
            if ($goods['stock'] <= 0) {
                $this->error('商品库存不足');
            }
            $base = Config::find(19);
            $price = $base['value'];  //价格
            if ($user['money'] < $price) {
                return errMsg(400, '您的余额不足,请充值');
            }
            $today_start = strtotime(date('Y-m-d') . " 00:00:00");
            $today_end = strtotime(date('Y-m-d') . " 23:59:59");
            $shop_num = UserPintuanLog::where(['user_id' => $user['id']])
                ->where('createtime', '>=', $today_start)
                ->where('createtime', '<=', $today_end)
                ->count();
            if ($shop_num > 10) {
                $this->error('每日仅可抽奖10次');
            }
            $data = ['goods_price' => $price, 'member_price' => $user['money']];
            $this->success('获取成功', $data);
        }
        $this->error('无效请求');
    }


    /**
     *
     * 拼购商品支付
     */
    public function payment()
    {
        if ($this->request->isPost()) {
            $pay_password = input('pay_password');  //支付密码
            $goods_id = input('goods_id');  //商品id
            $address_id = input('address_id');  //地址id
            $sku_id = input('sku_id', '');  //规格id
            $remark = input('remark'); //备注
            if (empty($goods_id) || empty($address_id)) {
                return errMsg(400, '参数不全');
            }
            $user = User::find($this->auth->id);
            $goods = GoodsModel::where('id', $goods_id)
                ->field('id,image,name,desc,is_package,package,price,stock')
                ->find();
            if (!$goods) {
                return errMsg(400, '商品错误');
            }
            if ($goods['stock'] <= 0) {
                return errMsg(400, '商品库存不足');
            }
            $today_start = strtotime(date('Y-m-d') . " 00:00:00");
            $today_end = strtotime(date('Y-m-d') . " 23:59:59");
            $shop_num = UserPintuanLog::where(['user_id' => $user['id']])
                ->where('createtime','between',[$today_start,$today_end])
                ->count();
            if ($shop_num > 10) {
                $this->error('每日仅可抽奖10次');
            }
            if (empty($pay_password)) {
                $this->error('请输入密码');
            }
            $pwd = getPassword($pay_password, $user['pay_salt']);
            if ($pwd != $user['pay_password']) {
                $this->error('支付密码错误');
            }
            $base = Config::find(19);
            $price = $base['value'];
            if ($user['money'] < $price) {
                return errMsg(400, '您的余额不足,请充值');
            }
            $zhong = -1; //是否中奖
            $this_num = $user['alerday_pin_total'] + 1;
            if ($this_num > $user['choujiang_max_num'] && $user['zhongjiang_num'] < 10) { //抽奖次数 大于 最大抽奖次数 必中
                $zhong = 1;
            }
            $zhong_array = explode(',', $user['winning_num']);
            if (in_array($this_num, $zhong_array) && $user['zhongjiang_num'] < 10) {
                $zhong = 1;
            }
            $spec = '';
            $address = Address::find($address_id);
            $jiangli_money = 0;//奖励红包
            $jiangli_score = 0;//奖励积分
            $all_money = 0;
            if($zhong != 1){
                $jiangli_money = $price * floatval($base['money_bili']/100); //奖励红包
                $jiangli_score = $price * floatval($base['score_bili']/100); //奖励积分
                $all_money = $jiangli_money + $price;
            }
            Db::startTrans();
            try{
                $pintuan_log = [
                    'user_id' => $this->user_id,
                    'goods_id' => $goods_id,
                    'sku_ids' => $sku_id,
                    'sku_values' => $spec,
                    'dangqian_num' => $this_num,
                    'score' => $jiangli_score,
                    'money' => $jiangli_money,
                    'status' => $zhong
                ];  //拼团记录
                $add_pintuan_log = PintuanLog::create($pintuan_log);
                Goods::where('id',$goods_id)
                    ->inc('sales')
                    ->dec('stock')
                    ->update();
                if ($zhong != 1) {  //没有拼中
                    //不中 积分+ 红包+ 退899
//                类型:1=未拼中奖励积分,2=助力积分,3=拼中十次奖励积分,4=购买商品扣除积分
                    $score_log = [
                        'title' => '未拼中返积分',
                        'goods_id' => $goods_id,
                        'score' => $jiangli_score,
                        'type' => 1,
                        'status' => 1,
                        'user_id' => $this->user_id,
                    ];
                    $money_log = [
                        'title' => '未拼中返红包',
                        'goods_id' => $goods_id,
                        'money' => $jiangli_score,
                        'type' => 2,
                        'status' => 1,
                        'user_id' => $this->user_id,
                    ];
                    //类型:1=充值,2=未拼中,奖励金额,3=未拼中返回拼购金,4=拼中10次返回奖励,5=助力红包,6=拼购支付,7=提现,8=运费扣除,9=拒绝提现 返回余额
                    $money_log1 = [
                        'title' => '未拼中返拼购金',
                        'goods_id' => $goods_id,
                        'money' => $price,
                        'type' => 3,
                        'status' => 1,
                        'user_id' => $this->user_id,
                    ];

                    ScoreLog::create($score_log);  //奖励积分变动
                    MoneyLog::create($money_log);  //奖励红包 余额变动
                    MoneyLog::create($money_log1); //返回拼购金 余额变动
                }
                else {  //拼中  加订单
                    //中了 发货 订单+
                    $order = [
                        'out_trade_no' => setCode(),
                        'user_id' => $this->user_id,
                        'goods_id' => $goods_id,
                        'sku_ids' => $sku_id,
                        'sku_values' => $spec,
                        'goods_name' => $goods['name'],
                        'goods_image' => $goods['image'],
                        'num' => $num,
                        'pay_price' => $price,
                        'package' => $package,
                        'address_id' => $address_id,
                        'address_name' => $address['name'],
                        'address_phone' => $address['phone'],
                        'address' => $address['address'],
                        'remark' => $remark,
                        'type' => 1,
                        'status' => 1,
                        'pintuan_id' => $add_pintuan_log['id']
                    ];
                    GoodsOrder::create($order);
                }
                $memebr_arr = [
                    'choujing_today_num' => $user['choujing_today_num'] + 1, //今日抽奖+1
                    'choujiang_num' => $this_num,  //当前抽奖次数
                    'choujiang_all_num' => $user['choujiang_all_num'] + 1,  //累计抽奖次数
                    'zhongjiang_num' => $zhong == 1 ? $user['zhongjiang_num'] + 1 : $user['zhongjiang_num'],//中奖次数
                    'zhongjiang_all_num' => $zhong == 1 ? $user['zhongjiang_all_num'] + 1 : $user['zhongjiang_all_num'],//累计中奖次数
                    'today_money' => $user['today_money'] + $jiangli_money,//今日拼购奖励
                    'money' => $user['money'] + $all_money,//余额
                    'score' => $user['score'] + $jiangli_score
                ];
                user::where('id',$this->user_id)->update($memebr_arr);
                $user = user::find($this->user_id);
                if($user['zhongjiang_num'] == 10){  //连续拼中10次
                    //重新生成中奖记录
                    $active_data = Lever::select()->toArray();  //等级数据
                    foreach ($active_data as $v) {
                        if ($user['active_all'] >= $v['start'] && $user['active_all'] <= $v['end']) {  //找出0活跃度在哪个范围里
                            $max_num = $v['choujing_max_num'];
                        }else{
                            $max_num = 400;
                        }
                    }
                    $base_chouji = PintuanBase::select();
                    $cishu = [];
                    foreach ($base_chouji as $v) {
                        $num = randomNums($v['start_num'], $v['end_num'], $v['zhongjiang_num']);
                        $cishu = array_merge($num, $cishu);
                    }
                    sort($cishu);  //按升序排序
                    $res = array_values($cishu);
                    if ($max_num != 400) {
                        $cha = 400 / $max_num;     //以前的最大数和当前的最大数的差
                        $res = [];
                        foreach ($cishu as $v) {  //根据抽中次数的缩小比例 把要抽中的次数缩小同样的比例
                            $num = ceil($v / $cha);
                            $res[] = $num;
                        }
                        $res = array_unique($res);  //去重
                        sort($res);
                        $res = array_values($res);
                        if (count($res) < 10) {
                            $res = $this->getNum($res, 1, 400, 10 - count($res));
                        }
                    }
                    $winning_num = implode(',', $res);
                    $user_total = [
                        'choujiang_num'=>0,//当前抽奖次数
                        'zhongjiang_num'=>0,//当前中奖次数
                        'winning_num'=>$winning_num,
                        'dongjie_money'=>$user['dongjie_money'] + $base['money'],//冻结金额
                        'score'=>$user['score']+$base['score'],
                    ];
                    //类型:1=未拼中奖励积分,2=助力积分,3=拼中十次奖励积分,4=购买商品扣除积分
                    $score_total = [
                        'title' => '拼中十次奖励积分',
                        'goods_id' => $goods_id,
                        'score' => $base['score'],
                        'type' => 3,
                        'status' => 1,
                        'user_id' => $this->user_id,
                    ];
                    //类型:1=充值,2=未拼中,奖励金额,3=未拼中返回拼购金,4=拼中10次返回奖励,5=助力红包,6=拼购支付,7=提现,8=运费扣除,9=拒绝提现 返回余额
                    $money_total = [
                        'title' => '拼中十次奖励红包',
                        'goods_id' => $goods_id,
                        'money' =>  $base['score'],
                        'type' => 4,
                        'status' => 1,
                        'user_id' => $this->user_id,
                    ];
                    user::where('id',$this->user_id)->update($user_total);
                    ScoreLog::create($score_total);
                    MoneyLog::create($money_total);
                }
                // 提交事务
                Db::commit();
                return sucessMsg(200,'拼购成功',['res'=>$zhong]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return errMsg(400,'拼购失败'.$e->getMessage());
            }


        }
        return errMsg(400, '非法请求');
    }


    /**$arr  数组 已经确认要抽中的次数 的数组
     * $min 最小值
     * $max 最大值
     * $num 个数
     */
    public function getNum($arr, $min, $max, $num)
    {
        if (!$num) {
            foreach ($arr as $k => $v) {
                if ($v > $max) {
                    unset($arr[$k]);
                    return $this->getNum($arr, $min, $max, $num + 1);
                }
            }
            return $arr;
        }
        $str = mt_rand($min, $max);
        if (in_array($str, $arr)) {
            return $this->getNum($arr, $min, $max, $num);
        } else {
            $arr[] = $str;
            return $this->getNum($arr, $min, $max, $num - 1);
        }
    }
}